package com.shanling.shanlingcontroller.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkplay.lpvr.avslib.LPAVSManager;
import com.linkplay.lpvr.avslib.LPAlexaAccount;
import com.linkplay.lpvr.lpvrbean.interfaces.templateruntime.LPAVSMessage;
import com.linkplay.lpvr.lpvrbean.interfaces.templateruntime.LPAVSRenderPlayerInfo;
import com.linkplay.lpvr.lpvrbean.interfaces.templateruntime.LPAVSWeatherTemplate;
import com.linkplay.lpvr.lpvrlistener.AVSListener;
import com.qualcomm.qti.libraries.gaia.GAIA;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.adapter.CommonAdapter;
import com.shanling.shanlingcontroller.adapter.ViewHolder;
import com.shanling.shanlingcontroller.base.BaseAppCompatActivity;
import com.shanling.shanlingcontroller.base.BaseAppManager;
import com.shanling.shanlingcontroller.bean.AlexaPlayInfoEvent;
import com.shanling.shanlingcontroller.bean.BluetoothState;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.bean.MainItemBean;
import com.shanling.shanlingcontroller.bean.MybluetoothDevice;
import com.shanling.shanlingcontroller.bean.WeatherEvent;
import com.shanling.shanlingcontroller.services.csr.MainGaiaManager;
import com.shanling.shanlingcontroller.services.csr.VersionGaiaManager;
import com.shanling.shanlingcontroller.ui.fragment.DeviceFragment;
import com.shanling.shanlingcontroller.ui.fragment.MusicFragment;
import com.shanling.shanlingcontroller.utils.ThreadPoolProxyFactory;
import com.shanling.shanlingcontroller.utils.ToastUtils;
import com.shanling.shanlingcontroller.utils.netstatus.NetUtils;
import com.shanling.shanlingcontroller.view.AlexaStatePop;
import com.shanling.shanlingcontroller.view.TopMiddlePopup;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseAppCompatActivity implements AdapterView.OnItemClickListener, VersionGaiaManager.VersionGaiaManagerListener {
    @BindView(R.id.iv_touxiang)
    ImageView ivTouxiang;
    @BindView(R.id.tv_blename)
    TextView tvBlename;
    @BindView(R.id.iv_list)
    ImageView ivList;
    @BindView(R.id.rl_blelist)
    RelativeLayout rlBlelist;
    @BindView(R.id.iv_ble)
    ImageView ivBle;
    @BindView(R.id.fl_main)
    FrameLayout flMain;
    @BindView(R.id.iv_music)
    ImageView ivMusic;
    @BindView(R.id.tv_music)
    TextView tvMusic;
    @BindView(R.id.ll_music)
    LinearLayout llMusic;
    @BindView(R.id.iv_device)
    ImageView ivDevice;
    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.ll_device)
    LinearLayout llDevice;
    @BindView(R.id.iv_take)
    ImageView ivTake;
    @BindView(R.id.drawer)
    DrawerLayout drawer;
    @BindView(R.id.iv_user)
    ImageView ivUser;
    @BindView(R.id.lv_action)
    ListView lvAction;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.rl_bg)
    RelativeLayout rlBg;
    private int type = 0;//0显示devicefragment  1 显示musicfragment
    private CommonAdapter<MainItemBean> mainItemBeanCommonAdapter;
    private List<MainItemBean> mainItemBeans;
    private FragmentManager fManager;//管理Fragment界面
    private MusicFragment musicFragment;
    private DeviceFragment deviceFragment;
    private FragmentTransaction transaction;
    private TopMiddlePopup topMiddlePopup;
    public LPAVSManager mLinkPlayAVSManager;
    private LPAlexaAccount mLPAlexaAccount;
    private AlexaStatePop alexaStatePop;
    private int state;
    private static final int linkPlayAVSMessageCome=1;
    private static final int recordMeterLevel=2;
    private static final int linkPlayAVSSpeechStateChange=3;
    private  Runnable runnable;
    private  VersionGaiaManager versionGaiaManager;

    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what){
               case linkPlayAVSMessageCome:
                   onLinkPlayAVSMessageCome((LPAVSMessage) msg.obj);
                   break;
               case recordMeterLevel:
                   onRecordMeterLevel((float) msg.obj);
                   break;
               case linkPlayAVSSpeechStateChange:
                   onLinkPlayAVSSpeechStateChange((int) msg.obj);
                   break;
           }
        }
    };

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setStatusBarFullTransparent();
        setDrawerLayoutFitSystemWindow();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViewsAndEvents() {
        fManager = getSupportFragmentManager();
        mLinkPlayAVSManager = LPAVSManager.getInstance(this);
        @GAIA.Transport int transport = GAIA.Transport.BR_EDR;
        versionGaiaManager= new VersionGaiaManager(this,transport);
        mLPAlexaAccount = LPAVSManager.getInstance(this).getAccount();
        setChoiceItem(0);
        setUi();
        alexaStatePop = new AlexaStatePop(this);
        List<MybluetoothDevice> mybluetoothDevices = LitePal.findAll(MybluetoothDevice.class);
        topMiddlePopup = new TopMiddlePopup(this, mybluetoothDevices);
        topMiddlePopup.setOnItemClickListener(new TopMiddlePopup.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (!mybluetoothDevices.get(position).getMac().equals(preferenceUtil.getBleMac())) {
                    String mac = preferenceUtil.getBleMac();
                    onChange(mybluetoothDevices.get(position), mac);
                }
            }
        });
        mLinkPlayAVSManager.registerAVSListener(mAVSListener);
        if(customApplication.isConnected()&&preferenceUtil.getBleType()==3){
            versionGaiaManager.getInformation();
        }
    }


    public void setUi(){
        switch (preferenceUtil.getBleType()){
            case 1:
                rlBg.setVisibility(View.VISIBLE);
                llMusic.setVisibility(View.VISIBLE);
                llDevice.setVisibility(View.VISIBLE);
                ivTake.setVisibility(View.VISIBLE);
                break;
            case 2:
                rlBg.setVisibility(View.VISIBLE);
                llMusic.setVisibility(View.VISIBLE);
                llDevice.setVisibility(View.VISIBLE);
                ivTake.setVisibility(View.GONE);
                break;
            case 3:
                rlBg.setVisibility(View.GONE);
                llMusic.setVisibility(View.GONE);
                llDevice.setVisibility(View.GONE);
                ivTake.setVisibility(View.GONE);
                break;
        }
    }
    private void onChange(MybluetoothDevice mybluetoothDevice, String mac) {
        preferenceUtil.setBleType(mybluetoothDevice.getType());
        preferenceUtil.setBleMac(mybluetoothDevice.getMac());
        preferenceUtil.setBleName(mybluetoothDevice.getName());
        tvBlename.setText(mybluetoothDevice.getName());
        setUi();
        EventBus.getDefault().post(new EventCenter<>(Constants.BLE_CHANGE, mac));
    }

    private void setChoiceItem(int index) {
        transaction = fManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                tvDevice.setSelected(true);
                ivDevice.setSelected(true);
                ivMusic.setSelected(false);
                tvMusic.setSelected(false);
                ivList.setVisibility(View.VISIBLE);
                ivBle.setImageResource(R.drawable.nav_add_device);
                type = 0;
                tvBlename.setText(preferenceUtil.getBleName());
                if (deviceFragment == null) {
                    deviceFragment = new DeviceFragment();
                    transaction.add(R.id.fl_main, deviceFragment);
                } else {
                    transaction.show(deviceFragment);
                }
                break;
            case 1://
                tvDevice.setSelected(false);
                ivDevice.setSelected(false);
                ivMusic.setSelected(true);
                tvMusic.setSelected(true);
                type = 1;
                ivList.setVisibility(View.GONE);
                tvBlename.setText(getString(R.string.my_music));
                ivBle.setImageResource(R.drawable.nav_icon_player);
                if (musicFragment == null) {
                    musicFragment = new MusicFragment();
                    transaction.add(R.id.fl_main, musicFragment);
                } else {
                    transaction.show(musicFragment);
                }
                if (topMiddlePopup.isShowing()) {
                    topMiddlePopup.dismiss();
                }
                break;
        }
        transaction.commit();
    }
    /**
     * 隐藏片段
     *
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (deviceFragment != null) {
            transaction.hide(deviceFragment);
        }
        if (musicFragment != null) {
            transaction.hide(musicFragment);
        }
    }

    @Override
    protected void initData() {
        mainItemBeans = new ArrayList<>();
        mainItemBeans.add(new MainItemBean(getString(R.string.Bluetooth_devicecontrol), R.drawable.leftbar_bluetooth));
        mainItemBeans.add(new MainItemBean(getString(R.string.setting), R.drawable.leftbar_set));
        mainItemBeans.add(new MainItemBean(getString(R.string.User_guide), R.drawable.leftbar_guide));
        mainItemBeans.add(new MainItemBean(getString(R.string.about), R.drawable.leftbar_about));
        mainItemBeanCommonAdapter = new CommonAdapter<MainItemBean>(this, mainItemBeans, R.layout.item_leftbar) {
            @Override
            public void convert(ViewHolder helper, int position, MainItemBean item) {
                ImageView ivaction = helper.getView(R.id.iv_action);
                TextView tv_action = helper.getView(R.id.tv_action);
                ivaction.setImageResource(item.getSrc());
                tv_action.setText(item.getAction());
            }
        };
        lvAction.setAdapter(mainItemBeanCommonAdapter);
        lvAction.setOnItemClickListener(this);

    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.BLUETOOTH_STATE:
                BluetoothState state = (BluetoothState) eventCenter.getData();
                if (state == null) {
                    return;
                }
                switch (state.getState()) {
                    case Constants.DISCONNECTED:
                        if (alexaStatePop.isShowing()) {
                            alexaStatePop.dismiss();
                        }
                        break;
                    case Constants.CONNECTED:
                        if (type == 0) {
                            tvBlename.setText(preferenceUtil.getBleName());
                        }
                        if(preferenceUtil.getBleType()==3){
                            versionGaiaManager.getInformation();
                        }
                        setUi();
                        break;
                }
                break;
            case  Constants.GAIA_PACKET:
                byte[] data = (byte[]) eventCenter.getData();
                Log.e("weiyu","数据"+ Arrays.toString(data));
                if(versionGaiaManager!=null){
                    versionGaiaManager.onReceiveGAIAPacket(data);
                }
                break;


        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        if (topMiddlePopup.isShowing()) {
            topMiddlePopup.dismiss();
        }
    }


    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }


    private long exitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showToast(this, R.string.press_again_to_exit);
                exitTime = System.currentTimeMillis();
            } else {
                BaseAppManager.getInstance().exit(false);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.iv_touxiang, R.id.rl_blelist, R.id.iv_ble, R.id.ll_music, R.id.ll_device, R.id.iv_take, R.id.iv_user})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_touxiang:
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    drawer.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.rl_blelist:
                if (type == 0) {
                    topMiddlePopup.show(rlBlelist);
                }
                break;
            case R.id.iv_ble:
                if (type == 0) {
                    EventBus.getDefault().post(new EventCenter<>(Constants.BLE_CHANGE, preferenceUtil.getBleMac()));
                    readyGo(BleActivity.class);
                } else {
                    readyGo(MusicPlayActivity.class);
                }
                break;
            case R.id.ll_music:
                setChoiceItem(1);
                break;
            case R.id.ll_device:
                setChoiceItem(0);
                break;
            case R.id.iv_take:
                boolean networkAvailable = NetUtils.isNetworkAvailable(this);
                if (!networkAvailable) {
                    ToastUtils.showToast(this, R.string.error1013);
                    return;
                }
                if (mLPAlexaAccount.getState() != LPAlexaAccount.LpAlexaAccountState.LP_ALEXA_ACCOUNT_VALID) {
                    return;
                }
                if (customApplication.isConnected() && preferenceUtil.getBleType() == 1) {
                    mLinkPlayAVSManager.startRecognize();
                } else {
                    ToastUtils.showToast(this, R.string.remind_hint);
                }
                break;
            case R.id.iv_user:
                readyGo(UserActivity.class);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0://跳转蓝牙控制页面
                readyGo(BleDeviceListActivity.class);
                break;
            case 1:
               // readyGo(BleDevicecontrolActivity.class);
                break;
            case 2:
                break;
            case 3:
                readyGo(AboutActivity.class);
                break;
        }
    }

    public void  onLinkPlayAVSMessageCome(LPAVSMessage lpavsMessage){
        if (lpavsMessage instanceof LPAVSRenderPlayerInfo) {
            LPAVSRenderPlayerInfo info = (LPAVSRenderPlayerInfo) lpavsMessage;
            EventBus.getDefault().postSticky(new AlexaPlayInfoEvent(info));
            readyGo(AlexaMusicActivity.class);
        } else if (lpavsMessage instanceof LPAVSWeatherTemplate) {
            LPAVSWeatherTemplate weatherTemplate = (LPAVSWeatherTemplate) lpavsMessage;
            EventBus.getDefault().postSticky(new WeatherEvent(weatherTemplate));
            readyGo(WeatherActivity.class);
        }
    }

    public void onRecordMeterLevel(float v){
        alexaStatePop.show(ivTake);
        if (state == 1) {
            alexaStatePop.updateAnimation(v);
        }
    }

    public void  onLinkPlayAVSSpeechStateChange(int i){
        switch (i) {
            case 0://LP_SPEECH_STATE_IDLE
                Log.e("weiyu", "空闲");
                alexaStatePop.stop();
                alexaStatePop.dismiss();
                state = 0;
                break;
            case 1://LP_SPEECH_STATE_LISTENING
                Log.e("state", "听");
                alexaStatePop.listen();
                state = 1;
                break;
            case 2://LP_SPEECH_STATE_PROCESSING
                state = 2;
                alexaStatePop.think();
                break;
            case 3://LP_SPEECH_STATE_SPEAKING
                Log.e("state", "说");
                alexaStatePop.speak();
                state = 3;
                break;
            case 4://LP_SPEECH_STATE_ERROR
                alexaStatePop.stop();
                alexaStatePop.dismiss();
                state = 4;
                break;
        }

    }


    private AVSListener mAVSListener = new AVSListener() {
        @Override
        public void linkPlayAVSMessageCome(LPAVSMessage lpavsMessage) {
            if (lpavsMessage == null) {
                return;
            }
            Message message=Message.obtain();
            message.what=linkPlayAVSMessageCome;
            message.obj=lpavsMessage;
            handler.sendMessage(message);
        }
        @Override
        public void recordMeterLevel(float v) {
            Message message=Message.obtain();
            message.what=recordMeterLevel;
            message.obj=v;
            handler.sendMessage(message);
        }

        @Override
        public void linkPlayAVSSpeechStateChange(int i) {
            Message message=Message.obtain();
            message.what=linkPlayAVSSpeechStateChange;
            message.obj=i;
            handler.sendMessage(message);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (topMiddlePopup.isShowing()) {
            topMiddlePopup.dismiss();
            topMiddlePopup = null;
        }
        if (alexaStatePop.isShowing()) {
            alexaStatePop.dismiss();
            alexaStatePop = null;
        }
        if (runnable != null) {
            ThreadPoolProxyFactory.getNormalThreadPoolProxy().remove(runnable);
        }
        mLinkPlayAVSManager.unRegisterAVSListener(mAVSListener);
        handler.removeCallbacksAndMessages(null);
    }
private boolean isSend;
    @Override
    public boolean sendGAIAPacket(byte[] packet) {
        runnable=new Runnable() {
            @Override
            public void run() {
                isSend=CustomApplication.getInstance().getmGAIABREDRProvider().sendGAIAUpgradePacket(packet, true) ;
            }
        };
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(runnable);
        return true;
    }

    @Override
    public void onGetAPIVersion(int versionPart1, int versionPart2, int versionPart3) {
        Log.e("weiyu","得到版本号"+versionPart1 + "." + versionPart2 + "." + versionPart3);
        String version = versionPart1 + "." + versionPart2 + "." + versionPart3;
        MybluetoothDevice mybluetoothDevice = new MybluetoothDevice();
        mybluetoothDevice.setCurrent_Version(version);
        mybluetoothDevice.updateAll("mac = ?", preferenceUtil.getBleMac());
        EventBus.getDefault().post(new EventCenter<>(Constants.UPGRADEFINISH, true));
    }
}
